﻿using System;
using System.Collections;
using System.Text;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;

namespace AdvancedLookup
{
    public class AdvancedLookupFieldControl : BaseFieldControl
    {
        const string ClientScriptOnLoad = "ClientScriptOnLoad";

        bool _accessListOk = true;

        public string ClientListValues = "LookupListValue_";


        private readonly HtmlInputText _lookupTextHtmlInputText = new HtmlInputText();

        private readonly HiddenField _lookupTextHiddenField = new HiddenField();

        AdvancedLookupField _currentAdvancedLookupField;

        public Label ErrorLabel;


        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            SPFieldLookupValue fieldVal = null;

            if (ControlMode == SPControlMode.Edit || ControlMode == SPControlMode.Display)
            {
                if (ListItemFieldValue != null)
                {
                    fieldVal = ListItemFieldValue as SPFieldLookupValue;
                }
                else
                {
                    fieldVal = new SPFieldLookupValue();
                }
            }

            if (ControlMode == SPControlMode.New)
            {
                fieldVal = new SPFieldLookupValue();
            }

            if (fieldVal != null)
            {
                _lookupTextHiddenField.Value = fieldVal.LookupId.ToString();

                _lookupTextHtmlInputText.Value = fieldVal.LookupValue;
            }
        }

        public override void Validate()
        {
            if (ControlMode == SPControlMode.Display || !IsValid)
            {
                return;
            }

            base.Validate();

            SPFieldLookupValue spFieldLookupValue = Value as SPFieldLookupValue;

            if (spFieldLookupValue != null && (spFieldLookupValue.LookupId == 0 && !string.IsNullOrEmpty(spFieldLookupValue.LookupValue)))
            {
                ErrorMessage = string.Format("В поле {0}, введены неправильные данные", Field.Title);

                IsValid = false;

                return;
            }

            if (Field.Required && spFieldLookupValue != null && (spFieldLookupValue.LookupId == 0 && string.IsNullOrEmpty(spFieldLookupValue.LookupValue)))
            {
                //ErrorMessage = string.Format("Поле {0}, должно содержать данные", Field.Title);

                ErrorMessage = "Необходимо задать значение для этого обязательного поля.";

                IsValid = false;

                return;
            }
        }


        /// <summary>
        /// DefaultTemplate is the ID of the template defined
        /// in the user control
        /// </summary>
        protected override string DefaultTemplateName
        {
            get
            {
                return "AdvancedLookupFieldControl";
            }
        }

        public override object Value
        {
            get
            {
                try
                {
                    return new SPFieldLookupValue(int.Parse(_lookupTextHiddenField.Value), _lookupTextHtmlInputText.Value);
                }
                catch (Exception)
                {
                }

                return new SPFieldLookupValue();
            }
            set
            {
                EnsureChildControls();

                base.Value = value as SPFieldLookupValue;
            }
        }

        protected SPListItem GetListItem(AdvancedLookupField advancedAdvancedLookupField, int fieldId)
        {
            SPListItem spListItem = null;

            if (advancedAdvancedLookupField != null && fieldId > 0)
            {
                SPSite spSite = GetContextSite(Context);

                using (SPWeb spWeb = spSite.OpenWeb(advancedAdvancedLookupField.LookupWebId))
                {
                    SPListCollection spListCollection = spWeb.Lists;

                    SPList spList = spListCollection[new Guid(advancedAdvancedLookupField.LookupList)];

                    SPListItemCollection spListItemCollection = spList.Items;

                    spListItem = spListItemCollection.GetItemById(fieldId);
                }
            }

            return spListItem;
        }

        /// <summary>
        /// CreateChildControls is used to define the controls used
        /// by the custom field.
        /// </summary>
        protected override void CreateChildControls()
        {
            if (Field != null && ControlMode != SPControlMode.Display)
            {
                Controls.Clear();

                _currentAdvancedLookupField = Field as AdvancedLookupField;

                if (_currentAdvancedLookupField != null)
                {
                    string initValueQueryStringParam = Page.Request.QueryString[_currentAdvancedLookupField.InitValueQueryStringParam];

                    SPListItem initSpListItem = null;

                    try
                    {
                        initSpListItem = GetListItem(_currentAdvancedLookupField, int.Parse(initValueQueryStringParam));
                    }
                    catch (Exception)
                    {
                    }

                    if (initSpListItem != null)
                    {
                        _lookupTextHtmlInputText.Value = initSpListItem[_currentAdvancedLookupField.LookupField] as string;

                        _lookupTextHiddenField.Value = initSpListItem.ID.ToString();
                    }

                    _lookupTextHtmlInputText.Size = 60;

                    _lookupTextHtmlInputText.Attributes.Add("autocomplete", "off");

                    HtmlImage htmlImage = new HtmlImage { Src = "/_layouts/images/addressbook.gif" };

                    htmlImage.Attributes.Add("onclick", "OpenDialog_" + UniqueID + "()");

                    htmlImage.Style.Add("padding-left", "5px");

                    Controls.Add(_lookupTextHiddenField);

                    Table table = new Table { CellPadding = 0, CellSpacing = 0 };

                    TableRow tableRow = new TableRow();

                    table.Rows.Add(tableRow);

                    TableCell tableCell = new TableCell();

                    tableCell.Controls.Add(_lookupTextHtmlInputText);

                    tableRow.Cells.Add(tableCell);

                    tableCell = new TableCell();

                    tableCell.Controls.Add(htmlImage);

                    tableRow.Cells.Add(tableCell);

                    Controls.Add(table);

                    Page.ClientScript.RegisterStartupScript(GetType(), string.Format("_{0}{1}", UniqueID, "ShowDialog"),
                                                            "<script type='text/javascript'> var qs = location.search.substring(1, location.search.length); var args = qs.split('&'); var vals = new Object(); for (var i = 0; i < args.length; i++) { var nameVal = args[i].split('='); var temp = unescape(nameVal[1]).split('+'); nameVal[1] = temp.join(' '); vals[nameVal[0]] = nameVal[1]; } function getqparam(paramname) { return vals[paramname]; }    function myDialogCallback_" + UniqueID + "(result,response) {  \n\t switch(result) { case SP.UI.DialogResult.cancel: alert('Cancel ' + response.message); break; case SP.UI.DialogResult.invalid: alert('Invalid ' + response.message); break; \n\t case SP.UI.DialogResult.ok: \n\t document.getElementById('" +
                                                            _lookupTextHtmlInputText.ClientID +
                                                            "').value = response.title; \n\t document.getElementById('" +
                                                            _lookupTextHiddenField.ClientID +
                                                            "').value = response.value; \n\t  break; } } function OpenDialog_" + UniqueID + "() { var options = SP.UI.$create_DialogOptions(); options.url = '" +
                                                            _currentAdvancedLookupField.DialogPageUrl + "?" +
                                                            _currentAdvancedLookupField.QueryStringParam +
                                                            "=' + getqparam('" +
                                                            _currentAdvancedLookupField.QueryStringParam +
                                                            "'); options.width=" +
                                                            _currentAdvancedLookupField.DialogWidth +
                                                            "; options.height=" +
                                                            _currentAdvancedLookupField.DialogHeight +
                                                            "; options.dialogReturnValueCallback = Function.createDelegate(null, myDialogCallback_" + UniqueID + "); SP.UI.ModalDialog.showModalDialog(options); } </script>",
                                                            false);



                    try
                    {
                        using (SPWeb spWeb = SPContext.Current.Site.OpenWeb())
                        {
                            try
                            {
                                spWeb.Site.CatchAccessDeniedException = false;

                                if (
                                    spWeb.Lists[new Guid(_currentAdvancedLookupField.LookupList)].
                                        DoesUserHavePermissions(SPBasePermissions.ViewListItems))
                                    _accessListOk = true;

                            }
                            catch (UnauthorizedAccessException)
                            {
                                _accessListOk = false;
                            }
                        }

                        ClientListValues += UniqueID;

                        _lookupTextHtmlInputText.Attributes.Add("onkeyup", JsOnKeyUp());

                        Page.ClientScript.RegisterClientScriptBlock(GetType(),
                                                                    string.Format("_{0}{1}", UniqueID,
                                                                                  ClientScriptOnLoad),
                                                                    JsOnLoad());

                    }
                    catch (Exception ex)
                    {
                        if (ErrorLabel != null)
                            ErrorLabel.Text = ex.Message;
                        else
                            throw new ApplicationException(ex.Message);

                    }

                    Page.ClientScript.RegisterClientScriptBlock(GetType(), string.Format("_{0}{1}", UniqueID, "Misc"),
                                                                " var qs = location.search.substring(1, location.search.length); var args = qs.split('&');var vals = new Object();for (var i = 0; i < args.length; i++) {var nameVal = args[i].split('=');var temp = unescape(nameVal[1]).split('+');nameVal[1] = temp.join(' ');vals[nameVal[0]] = nameVal[1];} function getqparam(paramname) { return vals[paramname]; } function CAMLCompliant(StrValue) { var CAMLString = StrValue.replace('<', '&lt;'); CAMLString = CAMLString.replace('>', '&gt;'); CAMLString = CAMLString.replace('&', '&amp;'); return CAMLString; } QueryHandler = null; function ResetBackGround() {this.style.backgroundColor = '';}function ChangeBackGround() { this.style.backgroundColor = 'lightblue'; } function ChangeBackGroundIE(event) { event.srcElement.parentNode.style.backgroundColor = 'lightblue'; } function ResetBackGroundIE(event) { event.srcElement.parentNode.style.backgroundColor = ''; }",
                                                                true);

                }
            }
        }

        private static string GetSoapReturnXmlFildName(string internalSpFieldName)
        {
            return string.Format("ows_{0}", internalSpFieldName);
        }

        private string JsOnLoad()
        {
            StringBuilder stringBuilder = new StringBuilder();

            stringBuilder.Append("<script language='javascript'>");
            stringBuilder.Append("\n\t");
            stringBuilder.AppendFormat("function SetTextField_{0}(strvalue,strstr)", UniqueID);
            stringBuilder.Append("\n\t");
            stringBuilder.Append("{");
            stringBuilder.Append("\n\t");
            stringBuilder.AppendFormat("var TextField = GetTargetField_{0}();", UniqueID);
            stringBuilder.Append("\n\t");
            stringBuilder.Append("if(TextField != null)");
            stringBuilder.Append("\n\t");
            stringBuilder.Append("{");
            stringBuilder.Append("\n\t");
            stringBuilder.Append("   TextField.value=strstr;");
            stringBuilder.Append("\n\t");
            stringBuilder.Append("}");
            stringBuilder.Append("\n\t");
            stringBuilder.AppendFormat("var TextFieldValue = GetTargetFieldValue_{0}();", UniqueID);
            stringBuilder.Append("\n\t");
            stringBuilder.Append("if(TextFieldValue != null)");
            stringBuilder.Append("\n\t");
            stringBuilder.Append("{");
            stringBuilder.Append("\n\t");
            stringBuilder.Append("TextFieldValue.value=strvalue;");
            stringBuilder.Append("\n\t");
            stringBuilder.Append("}");
            stringBuilder.Append("\n\t");
            stringBuilder.Append("}");
            stringBuilder.Append("\n\t");
            stringBuilder.AppendFormat("function GetTargetField_{0}()", UniqueID);
            stringBuilder.Append("\n\t");
            stringBuilder.Append("{");
            stringBuilder.Append("\n\t");
            stringBuilder.AppendFormat("return document.getElementById('{0}');", _lookupTextHtmlInputText.ClientID);
            stringBuilder.Append("\n\t");
            stringBuilder.Append("}");
            stringBuilder.Append("\n\t");
            stringBuilder.AppendFormat("function GetTargetFieldValue_{0}()", UniqueID);
            stringBuilder.Append("\n\t");
            stringBuilder.Append("{");
            stringBuilder.Append("\n\t");
            stringBuilder.AppendFormat("return document.getElementById('{0}');", _lookupTextHiddenField.ClientID);
            stringBuilder.Append("\n\t");
            stringBuilder.Append("}");
            stringBuilder.Append("\n\t");
            stringBuilder.AppendFormat("function AjaxAnswer_{0}()", UniqueID);
            stringBuilder.Append("\n\t");
            stringBuilder.Append("    {	 ");
            stringBuilder.Append("\n\t");
            stringBuilder.Append("        if (QueryHandler==null || typeof(QueryHandler)=='undefined')");
            stringBuilder.Append("\n\t");
            stringBuilder.Append("        {");
            stringBuilder.Append("\n\t");
            stringBuilder.Append("            return false;");
            stringBuilder.Append("\n\t");
            stringBuilder.Append("        }");
            stringBuilder.Append("\n\t");
            stringBuilder.Append("        if (QueryHandler.HttpObject.readyState==4 && QueryHandler.HttpObject.status==200)");
            stringBuilder.Append("\n\t");
            stringBuilder.Append("        {");
            stringBuilder.Append("\n\t");
            stringBuilder.Append("            window.status = 'SOAP request successfully processed...';");
            stringBuilder.Append("\n\t");
            stringBuilder.Append("            var xml = QueryHandler.HttpObject.responseXML;");

            stringBuilder.Append("\n\t");
            stringBuilder.Append("            if (xml.documentElement) ");
            stringBuilder.Append("\n\t");
            stringBuilder.Append("            {");
            stringBuilder.Append("\n\t");
            stringBuilder.Append("		        var rows = xml.documentElement.getElementsByTagName('z:row');");
            stringBuilder.Append("\n\t");
            stringBuilder.Append("		        if (rows.length==0)");
            stringBuilder.Append("\n\t");
            stringBuilder.Append(" 		        {");
            stringBuilder.Append("\n\t");
            stringBuilder.Append("			        rows = xml.documentElement.getElementsByTagName('row');");
            stringBuilder.Append("\n\t");
            stringBuilder.Append("		        }    		        		    ");
            stringBuilder.Append("\n\t");
            stringBuilder.Append("    		    QueryHandler.TargetObject.removeChild(QueryHandler.TargetObject.tBodies[0]);");
            stringBuilder.Append("\n\t");
            stringBuilder.Append("    		    QueryHandler.TargetObject.appendChild(document.createElement('TBODY'));");
            stringBuilder.Append("\n\t");
            stringBuilder.Append("		        if (rows.length > 0) ");
            stringBuilder.Append("\n\t");
            stringBuilder.Append("		        {                         ");
            stringBuilder.Append("\n\t");
            stringBuilder.Append("			        for (var i = 0; i < rows.length; i++) ");
            stringBuilder.Append("\n\t");
            stringBuilder.Append("			        {");
            stringBuilder.Append("\n\t");
            stringBuilder.Append("				        var LookupFieldValue = '';");
            stringBuilder.Append("\n\t");
            stringBuilder.Append("				        var IdValue = '';");
            stringBuilder.Append("\n\t");

            stringBuilder.Append(string.Format("				        if (rows[i].getAttributeNode('{0}')!=null)", GetSoapReturnXmlFildName(_currentAdvancedLookupField.LookupField)));



            stringBuilder.Append("\n\t");
            stringBuilder.Append("				        {");
            stringBuilder.Append("\n\t");

            stringBuilder.Append(string.Format("					        LookupFieldValue = rows[i].getAttributeNode('{0}').nodeValue;", GetSoapReturnXmlFildName(_currentAdvancedLookupField.LookupField)));

            stringBuilder.Append("\n\t");
            stringBuilder.Append("				        }");
            stringBuilder.Append("\n\t");
            stringBuilder.Append("				        if (rows[i].getAttributeNode('ows_ID')!=null)");
            stringBuilder.Append("\n\t");
            stringBuilder.Append("				        {");
            stringBuilder.Append("\n\t");
            stringBuilder.Append("					        IdValue = rows[i].getAttributeNode('ows_ID').nodeValue;");
            stringBuilder.Append("\n\t");
            stringBuilder.Append("				        }");
            stringBuilder.Append("\n\t");
            stringBuilder.Append("				        var NewRow = document.createElement('TR');");
            stringBuilder.Append("\n\t");
            stringBuilder.Append("				        var NewCell = document.createElement('TD');");
            stringBuilder.Append("\n\t");


            stringBuilder.Append("                       NewRow.setAttribute('lookuptxt',LookupFieldValue);");
            stringBuilder.Append("\n\t");

            stringBuilder.Append("                       NewRow.ID = IdValue;");
            stringBuilder.Append("\n\t");

            stringBuilder.Append("				        NewCell.appendChild(document.createTextNode(LookupFieldValue));");
            stringBuilder.Append("\n\t");
            stringBuilder.Append("                       NewCell.ID = IdValue;");
            stringBuilder.Append("\n\t");

            stringBuilder.Append("				        NewRow.appendChild(NewCell);");
            stringBuilder.Append("\n\t");


            string[] internalNames = _currentAdvancedLookupField.CamlQueryFields.Split(new[] { ';' });

            if (internalNames.Length > 0)
            {
                foreach (string fieldInternalName in internalNames)
                {
                    stringBuilder.Append("				        var addFieldValue = '';");
                    stringBuilder.Append("\n\t");


                    stringBuilder.Append(string.Format("				        if (rows[i].getAttributeNode('{0}')!=null)", GetSoapReturnXmlFildName(fieldInternalName)));
                    stringBuilder.Append("\n\t");
                    stringBuilder.Append("				        {");
                    stringBuilder.Append("\n\t");

                    stringBuilder.Append("				        NewCell = document.createElement('TD');");
                    stringBuilder.Append("\n\t");

                    stringBuilder.Append(string.Format("		addFieldValue = rows[i].getAttributeNode('{0}').nodeValue;", GetSoapReturnXmlFildName(fieldInternalName)));
                    stringBuilder.Append("\n\t");

                    stringBuilder.Append("var addFieldValueArr = addFieldValue.split(\"#\"); if(addFieldValueArr.length > 1) { addFieldValue =  addFieldValueArr[1]; }");
                    stringBuilder.Append("\n\t");

                    stringBuilder.Append("				        NewCell.appendChild(document.createTextNode(addFieldValue));");
                    stringBuilder.Append("\n\t");

                    stringBuilder.Append("				        NewRow.appendChild(NewCell);");
                    stringBuilder.Append("\n\t");

                    stringBuilder.Append("				        }");
                    stringBuilder.Append("\n\t");


                }
            }



            stringBuilder.Append("				        if(window.addEventListener)");
            stringBuilder.Append("\n\t");
            stringBuilder.Append("				        {");
            stringBuilder.Append("\n\t");
            stringBuilder.Append("				            NewRow.addEventListener('mouseover',ChangeBackGround,false);");
            stringBuilder.Append("\n\t");
            stringBuilder.AppendFormat("				            NewRow.addEventListener('click',SetFieldValue_{0},false);", UniqueID);
            stringBuilder.Append("\n\t");
            stringBuilder.Append("				            NewRow.addEventListener('mouseout',ResetBackGround,false);");
            stringBuilder.Append("\n\t");
            stringBuilder.Append("				        }");
            stringBuilder.Append("\n\t");
            stringBuilder.Append("				        else");
            stringBuilder.Append("\n\t");
            stringBuilder.Append("				        {");
            stringBuilder.Append("\n\t");
            stringBuilder.Append("				            NewRow.attachEvent('onmouseover',ChangeBackGroundIE);");
            stringBuilder.Append("\n\t");
            stringBuilder.AppendFormat("				            NewRow.attachEvent('onclick',SetFieldValueIE_{0});", UniqueID);
            stringBuilder.Append("\n\t");
            stringBuilder.Append("				            NewRow.attachEvent('onmouseout',ResetBackGroundIE);");
            stringBuilder.Append("\n\t");
            stringBuilder.Append("				        }");
            stringBuilder.Append("\n\t");
            stringBuilder.Append("				        QueryHandler.TargetObject.tBodies[0].appendChild(NewRow);");
            stringBuilder.Append("\n\t");
            stringBuilder.Append("			        }   					    ");
            stringBuilder.Append("\n\t");
            stringBuilder.Append("		        }		      ");
            stringBuilder.Append("\n\t");
            stringBuilder.Append("            }");
            stringBuilder.Append("\n\t");
            stringBuilder.Append("      }");
            stringBuilder.Append("\n\t");
            stringBuilder.Append("      else");
            stringBuilder.Append("\n\t");
            stringBuilder.Append("      {");
            stringBuilder.Append("\n\t");
            stringBuilder.Append("            window.status = 'SOAP request failed...';");
            stringBuilder.Append("\n\t");
            stringBuilder.Append("      }");
            stringBuilder.Append("\n\t");
            stringBuilder.Append("}  ");
            stringBuilder.Append("\n\t");
            stringBuilder.AppendFormat("function AjaxQuery_{0}(Host, SiteURL, ListName, Query, QueryOptions, ItemLimit,TgtObject)", UniqueID);
            stringBuilder.Append("\n\t");
            stringBuilder.Append("{  ");
            stringBuilder.Append("\n\t");
            stringBuilder.Append("	var SpCAMLQuery; ");
            stringBuilder.Append("\n\t");
            stringBuilder.Append("	this.HttpObject = null;	");
            stringBuilder.Append("\n\t");
            stringBuilder.Append("	this.TargetObject = document.getElementById(TgtObject);	");
            stringBuilder.Append("\n\t");
            stringBuilder.Append("	this.TargetObject.style.visibility='visible';	");
            stringBuilder.Append("\n\t");
            stringBuilder.Append("	SpCAMLQuery= '<?xml version=\"1.0\" encoding=\"utf-8\"?>';");
            stringBuilder.Append("\n\t");
            stringBuilder.Append("	SpCAMLQuery+='<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">';");
            stringBuilder.Append("\n\t");
            stringBuilder.Append("	SpCAMLQuery+='<soap:Body>';");
            stringBuilder.Append("\n\t");
            stringBuilder.Append("	SpCAMLQuery+='<GetListItems xmlns=\"http://schemas.microsoft.com/sharepoint/soap/\">'; ");
            stringBuilder.Append("\n\t");
            stringBuilder.Append("	SpCAMLQuery+='<listName>'+ListName+'</listName>' ;");
            stringBuilder.Append("\n\t");
            stringBuilder.Append("	SpCAMLQuery+='<rowLimit>'+ItemLimit+'</rowLimit>' ;");
            stringBuilder.Append("\n\t");
            stringBuilder.Append("	SpCAMLQuery+='<query>'+Query+'</query>' ;		");
            stringBuilder.Append("\n\t");

            if (internalNames.Length > 0)
            {
                stringBuilder.Append("	SpCAMLQuery+='<viewFields><ViewFields>' ;");

                foreach (string fieldInternalName in internalNames)
                {
                    stringBuilder.Append(string.Format("	SpCAMLQuery+='<FieldRef Name=\"{0}\" />' ;", fieldInternalName));
                }

                stringBuilder.Append("	SpCAMLQuery+='</ViewFields></viewFields>' ;");
            }

            stringBuilder.Append("\n\t");

            stringBuilder.Append("	SpCAMLQuery+='<queryOptions>'+QueryOptions+'</queryOptions>' ;	");
            stringBuilder.Append("\n\t");



            stringBuilder.Append("	SpCAMLQuery+='</GetListItems></soap:Body></soap:Envelope>' ;");
            stringBuilder.Append("\n\t");
            stringBuilder.Append("	var serverUrl = SiteURL+'/_vti_bin/Lists.asmx?wsdl' ;");
            stringBuilder.Append("\n\t");
            stringBuilder.Append("	if (this.HttpObject==null)");
            stringBuilder.Append("\n\t");
            stringBuilder.Append("	{");
            stringBuilder.Append("\n\t");
            stringBuilder.Append("		if (window.XMLHttpRequest)");
            stringBuilder.Append("\n\t");
            stringBuilder.Append("		{ ");
            stringBuilder.Append("\n\t");
            stringBuilder.Append("			this.HttpObject = new XMLHttpRequest();		");
            stringBuilder.Append("\n\t");
            stringBuilder.Append("		} ");
            stringBuilder.Append("\n\t");
            stringBuilder.Append("		else if (window.ActiveXObject)");
            stringBuilder.Append("\n\t");
            stringBuilder.Append("		{ ");
            stringBuilder.Append("\n\t");
            stringBuilder.Append("			this.HttpObject = new ActiveXObject(\"MSXML2.XMLHTTP.3.0\");");
            stringBuilder.Append("\n\t");
            stringBuilder.Append("		}");
            stringBuilder.Append("\n\t");
            stringBuilder.Append("	}	    ");
            stringBuilder.Append("\n\t");
            stringBuilder.Append("	this.HttpObject.open(\"POST\", SiteURL + \"/_vti_bin/lists.asmx\", true); 	");
            stringBuilder.Append("\n\t");
            stringBuilder.Append("	this.HttpObject.setRequestHeader(\"Content-Type\",\"text/xml; charset=utf-8\"); ");
            stringBuilder.Append("\n\t");
            stringBuilder.Append("	this.HttpObject.setRequestHeader(\"Host\", Host); ");
            stringBuilder.Append("\n\t");
            stringBuilder.Append("	this.HttpObject.setRequestHeader(\"SOAPAction\",\"http://schemas.microsoft.com/sharepoint/soap/GetListItems\");");
            stringBuilder.Append("\n\t");
            stringBuilder.AppendFormat("	this.readyStateChangeHandler = AjaxAnswer_{0};	", UniqueID);
            stringBuilder.Append("\n\t");
            stringBuilder.Append("	this.HttpObject.onreadystatechange = this.readyStateChangeHandler; 		");
            stringBuilder.Append("\n\t");
            stringBuilder.Append("	this.HttpObject.send(SpCAMLQuery); 	");
            stringBuilder.Append("\n\t");
            stringBuilder.Append("	window.status = \"SOAP request sent...\";");
            stringBuilder.Append("\n\t");
            stringBuilder.Append("}");
            stringBuilder.Append("\n\t");
            stringBuilder.AppendFormat("function SetFieldValue_{0}()", UniqueID);
            stringBuilder.Append("\n\t");
            stringBuilder.Append("{");
            stringBuilder.Append("\n\t");




            stringBuilder.AppendFormat("  SetTextField_{0}(this.ID,this.getAttribute('lookuptxt'));QueryHandler.TargetObject.style.visibility='hidden';", UniqueID);

            stringBuilder.Append("\n\t");
            stringBuilder.Append("}");
            stringBuilder.Append("\n\t");

            stringBuilder.AppendFormat("function SetFieldValueIE_{0}(event)", UniqueID);
            stringBuilder.Append("\n\t");
            stringBuilder.Append("{");
            stringBuilder.Append("\n\t");


            stringBuilder.AppendFormat("  SetTextField_{0}(event.srcElement.parentNode.ID,event.srcElement.parentNode.getAttribute('lookuptxt'));QueryHandler.TargetObject.style.visibility='hidden';", UniqueID);
            stringBuilder.Append("\n\t");
            stringBuilder.Append("}");
            stringBuilder.Append("\n\t");
            stringBuilder.Append("</script>");
            return stringBuilder.ToString();

        }


        string JsOnKeyUp()
        {
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.Append("\n\t");
            stringBuilder.AppendFormat("if(this.value != '' && this.value.length >= {0})", _currentAdvancedLookupField.Prefix);
            stringBuilder.Append("\n\t");
            stringBuilder.Append("{");
            stringBuilder.Append("\n\t");
            stringBuilder.Append("if((event.keyCode > 25 && event.keyCode<=90)||event.keyCode==8){");
            stringBuilder.Append("\n\t");
            stringBuilder.AppendFormat("QueryHandler = new AjaxQuery_{0}(", UniqueID);
            stringBuilder.Append("\n\t");
            stringBuilder.AppendFormat("\"http://{0}/\",", SPContext.Current.Site.HostName);
            stringBuilder.Append("\n\t");
            stringBuilder.AppendFormat("\"{0}\",", SPContext.Current.Web.Url);
            stringBuilder.Append("\n\t");
            stringBuilder.AppendFormat("unescape(\"{0}\"),", _currentAdvancedLookupField.LookupList);
            stringBuilder.Append("\n\t");
            stringBuilder.Append("\"");
            stringBuilder.Append(string.Format(_currentAdvancedLookupField.CamlQuery, "CAMLCompliant(this.value)"));

            stringBuilder.Append("\",");
            stringBuilder.Append("\n\t");
            stringBuilder.Append("\"<QueryOptions><IncludeMandatoryColumns>TRUE</IncludeMandatoryColumns></QueryOptions>\",");
            stringBuilder.Append("\n\t");
            stringBuilder.AppendFormat("{0},", _currentAdvancedLookupField.ItemLimit);
            stringBuilder.Append("\n\t");
            stringBuilder.AppendFormat("\"{0}\")", ClientListValues);
            stringBuilder.Append("\n\t");
            stringBuilder.Append("}");
            stringBuilder.Append("\n\t");
            stringBuilder.Append("}");
            stringBuilder.Append("\n\t");
            stringBuilder.Append("else if(this.value == '')");
            stringBuilder.Append("\n\t");
            stringBuilder.Append("{");
            stringBuilder.Append("\n\t");
            stringBuilder.AppendFormat("var TheTarget=document.getElementById(\"{0}\");TheTarget.removeChild(TheTarget.tBodies[0]);TheTarget.appendChild(document.createElement('TBODY'));", ClientListValues);
            stringBuilder.Append("\n\t");
            stringBuilder.Append("}");
            stringBuilder.Append("\n\t");
            return stringBuilder.ToString();
        }

        protected override void Render(HtmlTextWriter output)
        {
            base.Render(output);

            if (ControlMode == SPControlMode.Edit || ControlMode == SPControlMode.New)
            {
                if (_accessListOk)
                {
                    output.Write("<br/><table style=\"background-color:white;font-family:verdana;font-size:10px;position:absolute;z-index:100000\" id=\"{0}\"><tbody></tbody></table>", ClientListValues);
                }
                else
                {
                    output.Write("<br/><table style=\"background-color:white;color:red;position:absolute\"><tbody><tr><td>You don't have access to the source list</td></tr></tbody></table>");
                }
            }
        }
    }
}
